package cn.tedu.charging.cost.dao.repository.impl;

import cn.tedu.chaging.common.utils.JsonUtils;
import cn.tedu.charging.cost.dao.repository.CostRuleCacheRepository;
import cn.tedu.charging.cost.pojo.po.CostRulePO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
import reactor.util.annotation.Nullable;

import java.io.Serializable;
import java.util.*;

@Repository
public class CostRuleCacheRepositoryImpl implements CostRuleCacheRepository {

    private static final Logger log = LoggerFactory.getLogger(CostRuleCacheRepositoryImpl.class);
    /**
     * redis 常用的数据类型
     * string list hash set zset
     */
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public List<CostRulePO> getCostRuleByStationId(Integer stationId) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String costRuleKey = "COST_RULE_KEY_" + stationId;
        Serializable serializable = valueOperations.get(costRuleKey);
        if (serializable != null) {
            log.debug("从redis获取数据:{}",serializable);
            //todo 序列化bug
            return getCostRulePos(serializable);
        }
        return null;
    }
    /*
    *
    * 将从redis中取出的数据反序列化
    * */
    @Nullable
    private List<CostRulePO> getCostRulePos(Serializable serializable) {
        List<CostRulePO> costRulePOs = new ArrayList<>();
        List<LinkedHashMap<String,CostRulePO>> mapList = JsonUtils.fromJson(serializable.toString(),List.class);
        for (LinkedHashMap<String,CostRulePO> map : mapList) {
            CostRulePO costRulePO = JsonUtils.convertValue(map, CostRulePO.class);
            costRulePOs.add(costRulePO);
        }
    return costRulePOs;
    }

    @Override
    public void saveCostRule(Integer stationId,List<CostRulePO> costRulePO) {
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String costRuleKey = "COST_RULE_KEY_" + stationId;
        String json = JsonUtils.toJson(costRulePO);
        valueOperations.set(costRuleKey,json);
    }


}
